# -*- coding:utf-8 -*-
#
# @File     :auth
# @Author   :Yupeng
# @Date     :2018/10/26 17:33

from functools import wraps
from django.http import HttpRequest
from hte.error.handle import abort_on_error
from hte.error.models import HTEError
from hte.utils.general import GlobalRequestMiddleware
from .models.users import UserRole, User
from typing import List, Union, Tuple


def require_user_role_api(user_role: UserRole = UserRole.VERIFIED_USER, role_only: bool = False):
    """"
    修饰api view，指定身份的用户才可以访问
    :param user_role: 用户身份（UserRole枚举类型）
    :param role_only: 如果为True，则只有user_role身份的用户可以访问，否则权限大于等于user_role的用户都可以访问
    :return: None
    """

    def real_decorator(func):
        @wraps(func)
        def real_func(request, *args, **kwargs):
            user = request.user
            if not user.is_authenticated:
                abort_on_error(HTEError.UNAUTHORIZED)
            if role_only and user.role != user_role or not role_only and user.role > user_role:
                abort_on_error(HTEError.PERMISSION_DENIED)
            return func(request, *args, **kwargs)

        return real_func

    return real_decorator


def check_user_role_api(user_role: UserRole = UserRole.VERIFIED_USER, role_only: bool = False):
    """"
    使用此函数确保用户符合身份限制，否则中断请求，返回错误信息
    :param user_role: 用户身份（UserRole枚举类型 ）
    :param role_only: 如果为True，则只有user_role身份的用户可以访问，否则权限大于等于user_role的用户都可以访问
    :return: None
    """
    user = GlobalRequestMiddleware.get_current_request().user
    if not user.is_authenticated:
        abort_on_error(HTEError.UNAUTHORIZED)
    if role_only and user_role != user_role or not role_only and user.role > user_role:
        abort_on_error(HTEError.PERMISSION_DENIED)


def ensure_privacy(request: HttpRequest, user: Union[str, User], is_api=True):
    """
    使用此函数检测user是否为当前登录的用户，保证只能由user指定的用户访问，如果不是user，中断请求返回错误信息
    :param user:可以为用户的username，也可以为一个User对象
    :return:None
    """

    if isinstance(user, str):
        username = user
    elif isinstance(user, User):
        username = User.username
    else:
        username = None
    if username != request.user.username:
        abort_on_error(HTEError.PERMISSION_DENIED)


def is_the_same_user(user):
    if isinstance(user, str):
        username = user
    elif isinstance(user, User):
        username = user.username
    else:
        raise ValueError('user应该为User类型对象或用户名字符串')
    return username == GlobalRequestMiddleware.get_current_request().user.username


def login_required_api(func):
    """

    :param func:
    :return:
    """

    @wraps(func)
    def real_func(request: HttpRequest, *args, **kwargs):
        if not request.user.is_authenticated:
            abort_on_error(HTEError.UNAUTHORIZED)
        return func(request, *args, **kwargs)

    return real_func


def check_login():
    """

    :return:
    """
    user = GlobalRequestMiddleware.get_current_request().user
    if not user.is_authenticated:
        abort_on_error(HTEError.UNAUTHORIZED)
